package com.fuint.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuint.common.dto.ArticleDto;
import com.fuint.common.enums.StatusEnum;
import com.fuint.common.service.ArticleService;
import com.fuint.common.service.MerchantService;
import com.fuint.common.service.SettingService;
import com.fuint.common.service.StoreService;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.pagination.PaginationRequest;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.repository.mapper.MtArticleMapper;
import com.fuint.repository.model.MtArticle;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 文章服务接口
 *
 * Created by FSQ
 * CopyRight https://www.fuint.cn
 */
@Service
@AllArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<MtArticleMapper, MtArticle> implements ArticleService {

    private MtArticleMapper mtArticleMapper;

    /**
     * 系统设置服务接口
     * */
    private SettingService settingService;

    /**
     * 商户服务接口
     * */
    private MerchantService merchantService;

    /**
     * 店铺接口
     */
    private StoreService storeService;



    @Override
    public PaginationResponse<ArticleDto> queryArticleListByPagination(PaginationRequest paginationRequest) throws BusinessCheckException {

        Page<MtArticle> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtArticle> lambdaQueryWrapper = Wrappers.lambdaQuery();
        // 查询条件：文章状态！=已删除
        lambdaQueryWrapper.ne(MtArticle::getStatus, StatusEnum.DISABLE.getKey());
        //把controller层传入的参数拿出来，并且如果不为空的话就加入查询链
        String title = paginationRequest.getSearchParams().get("title") == null ? "" : paginationRequest.getSearchParams().get("title").toString();
        if (StringUtils.isNotBlank(title)) {
            lambdaQueryWrapper.like(MtArticle::getTitle, title);
        }
        String status = paginationRequest.getSearchParams().get("status") == null ? "" : paginationRequest.getSearchParams().get("status").toString();
        if (StringUtils.isNotBlank(status)) {
            lambdaQueryWrapper.eq(MtArticle::getStatus, status);
        }
        String merchantId = paginationRequest.getSearchParams().get("merchantId") == null ? "" : paginationRequest.getSearchParams().get("merchantId").toString();
        if (StringUtils.isNotBlank(merchantId)) {
            lambdaQueryWrapper.eq(MtArticle::getMerchantId, merchantId);
        }
        String merchantNo = paginationRequest.getSearchParams().get("merchantNo") == null ? "" : paginationRequest.getSearchParams().get("merchantNo").toString();
        // 根据商户编号查询商户id（编号：每家商户特有的。ID：商户表的自增主键）
        Integer mchId = merchantService.getMerchantId(merchantNo);
        // 如果商户id>0，则加上根据商户id查询的条件
        if (mchId > 0) {
            lambdaQueryWrapper.eq(MtArticle::getMerchantId, mchId);
        }
        // 店铺id
        String storeId = paginationRequest.getSearchParams().get("storeId") == null ? "" : paginationRequest.getSearchParams().get("storeId").toString();
        // 如果店铺id>0。需要文章的storeId为0或者和当前店铺id一致
        if (StringUtils.isNotBlank(storeId)) {
            lambdaQueryWrapper.and(wq -> wq
                    .eq(MtArticle::getStoreId, 0)
                    .or()
                    .eq(MtArticle::getStoreId, storeId));
        }
        lambdaQueryWrapper.orderByAsc(MtArticle::getSort);
        // 根据上面构造的条件查询文章
        List<MtArticle> articleList = mtArticleMapper.selectList(lambdaQueryWrapper);
        List<ArticleDto> dataList = new ArrayList<>();

        // 设置上传/下载图片的base路径
        String basePath = settingService.getUploadBasePath();
        for (MtArticle mtArticle : articleList) {
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(mtArticle, articleDto);
            // 设置图片的url路径（baseurl+图片相对地址）
            articleDto.setImage(basePath + mtArticle.getImage());
            dataList.add(articleDto);
        }

        //todo（待改进）：这里可以修改成mybatisplus的分页插件，这样不用自己写分页处理了
        //将查询到的文章列表进行分页处理，并封装成PaginationResponse对象返回。首先创建PageRequest对象设置当前页和每页大小，然后通过PageImpl构造分页对象，最后将分页信息、总页数、总元素数和内容设置到PaginationResponse对象中。
        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<ArticleDto> paginationResponse = new PaginationResponse(pageImpl, ArticleDto.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;

    }

    @Override
    public MtArticle addArticle(ArticleDto articleDto) throws BusinessCheckException {
        return null;
    }

    @Override
    public MtArticle queryArticleById(Integer id) throws BusinessCheckException {
        return null;
    }

    @Override
    public ArticleDto getArticleDetail(Integer id) throws BusinessCheckException {
        return null;
    }

    @Override
    public MtArticle updateArticle(ArticleDto articleDto) throws BusinessCheckException {
        return null;
    }

    @Override
    public List<MtArticle> queryArticleListByParams(Map<String, Object> params) throws BusinessCheckException {
        return Collections.emptyList();
    }
}
